import React from 'react'
import './index.less'
import { Upload, Select, Input, DatePicker } from 'antd';
import http from 'libs/http'
import manPhoto from 'images/student/boy-photo.png'
import womenPhoto from 'images/student/girl-photo.png'
import defaultPhoto from 'images/student/default-photo.png'
import moment from 'moment'
import { Dialog } from 'components';
import UpdateMobilePhoneModal from './UpdateMobilePhoneModal';
import VolidOldMobilePhoneModal from './VolidOldMobilePhoneModal';
import { timingSafeEqual } from 'crypto';

const { Option } = Select

export default class extends React.Component {
  state = {
    uploading: false,
    age: null,
    birthday: null,
    city: '',
    mobilePhone: '',
    orgId: null,
    orgName: '',
    realName: '',
    recommendPhone: '',
    sex: '',
    headImg: '',
    orgList: [],
    showUpdateMobilePhoneModal: false,
    showVolidOldMobilePhoneModal: false,
    realNameErr: ''
  }

  componentDidMount() {
    // 先获取机构列表，再获取用户信息，为了正常返显
    this.getOrgList()
    this.getUserInfo()
    this.getHeadImageUrl()
  }

  getUserInfo = () => {
    http.get('/student/info/getInfo').then(res => {
      const { age, birthday, city, mobilePhone, orgId, realName, recommendPhone, sex, } = res.data
      this.setState({
        age, birthday, city, mobilePhone, orgId, realName, recommendPhone, sex,
      })
    })
  }
  // 获取机构列表
  getOrgList = () => {
    http.get('/student/info/orgList').then(res => {
      this.setState({
        orgList: res.data
      }, this.getUserInfo)
    })
  }
  getHeadImageUrl = () => {
    http.get('/student/info/getHeadImageUrl').then(res => {
      const headImg = res.data
      headImg && this.setState({ headImg })
    })
  }

  beforeAvatarUpload = file => {
    const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isImg) {
      message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isImg && isLt2M;
  }

  handleAvatarChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({uploading: true});
    }
    else if (info.file.status === 'done') {
      this.setState({
        uploading: false,
        upload: true
      }, () => {
        this.getHeadImageUrl()
      })
    } else if (info.file.status === 'error') {
      t_alert("Upload failure ！");
      this.setState({
        uploading: false
      })
    }
  }
  handleSexChange = sex => {
    this.setState({ sex })
  }

  handleRealNameChange = e => {
    if(e.target.value == ''){
      this.setState({
        realName: e.target.value,
        realNameErr: '请输入学员姓名'
      })
    }else{
      this.setState({
        realName: e.target.value,
        realNameErr: ''
      })
    }
  }

  handleDateChange = birthday => {
    const text = moment(birthday, 'YYYY-MM-DD').fromNow();    
    let age = parseInt(text, 10);
    if (isNaN(age)) {    
      age = ''; 
    } 
    this.setState({ birthday, age })
  }

  handleEditMobile = () => {
    this.setState({
      showVolidOldMobilePhoneModal: true
    })
  }
  handleOrgChange = orgId => {
    this.setState({ orgId })
  }
  handleCloseUpdateMobileModal = () => {
    this.setState({
      showUpdateMobilePhoneModal: false
    })
  }
  handleSubmit = () => {
    const { birthday, realName, sex, orgId} = this.state
    if(realName == ''){
      this.setState({
        realNameErr: '请输入学员姓名'
      })
    }else{
      http.post('/student/info/saveInfo', { birthday: moment(birthday).format('YYYY-MM-DD'), realName, sex, orgId }).then(res => {
        Dialog({
          message: '保存成功！'
        })
      })
    }
  }
  // 验证旧手机号通过
  handleVolidOldPhoneConfirm = () => {
    this.setState({
      showUpdateMobilePhoneModal: true,
      showVolidOldMobilePhoneModal: false
    })
  }
  // 更换手机号成功
  handleChangeNewPhoneConfirm = () => {
    this.setState({
      showUpdateMobilePhoneModal: false,
      showVolidOldMobilePhoneModal: false
    })
    this.getUserInfo()
  }
  handleVolidOldPhoneClose = () => {
    this.setState({
      showVolidOldMobilePhoneModal: false
    })
  }
  render() {
    const {
      uploading,
      age,
      birthday,
      city,
      mobilePhone,
      orgId,
      orgName,
      realName,
      recommendPhone,
      orgList,
      sex,
      headImg,
      showUpdateMobilePhoneModal,
      realNameErr,
      showVolidOldMobilePhoneModal
    } = this.state
    const _headImg = headImg ? headImg : (sex === 1 ? manPhoto : (sex === 2 ? womenPhoto : defaultPhoto) )
    return (
      <div className="personal-information-container">
        {
          showVolidOldMobilePhoneModal ? 
            <VolidOldMobilePhoneModal 
              handleConfirm={this.handleVolidOldPhoneConfirm} 
              handleCloseModal={this.handleVolidOldPhoneClose}
            /> : null
        }
        {
          showUpdateMobilePhoneModal ? 
            <UpdateMobilePhoneModal 
              mobilePhone={mobilePhone}
              handleConfirm={this.handleChangeNewPhoneConfirm} 
              handleCloseModal={this.handleCloseUpdateMobileModal}/> : null
        }
        {
          showUpdateMobilePhoneModal || showVolidOldMobilePhoneModal ? <div className="mask"></div> : null
        }
        <div className="personal-information">
          <ul>
            <li className="head">
              <label>头像</label>
              <div>
                <img src={_headImg} />
                <Upload
                  name="file"
                  action="/student/info/uploadHeadImage"
                  showUploadList={false}
                  loading={uploading}
                  beforeUpload={this.beforeAvatarUpload}
                  onChange={this.handleAvatarChange}
                >
                  <span className="upload">上传头像</span>
                </Upload>
              </div>
            </li>
            <li>
              <label><i>*</i>学员姓名</label>
              <Input 
                placeholder="请输入学员姓名（必填项）" 
                value={realName} 
                onChange={this.handleRealNameChange} 
                className={realNameErr != '' ? 'err' : ''}
              />
              <span className="real-name">{realNameErr}</span>
            </li>
            <li>
              <label>学员性别</label>
              {/* <input placeholder="请选择学员性别" /> */}
              <Select 
                size="large" 
                style={{ width: 300, fontSize: 14, color: '#333' }} 
                onChange={this.handleSexChange}
                placeholder="请选择性别"
                value={sex}
              >
                <Option value={1}>男</Option>
                <Option value={2}>女</Option>
              </Select>
            </li>
            <li>
              <label>出生年月</label>
              {/* <input placeholder="请选择出生年月" /> */}
              <DatePicker 
                placeholder="请选择出生年月" 
                value={birthday ? moment(birthday, 'YYYY-MM-DD') : null}
                onChange={this.handleDateChange}
              />
            </li>
            <li>
              <label>学员年龄</label>
              {age ? <span>{age}岁</span> : null}
            </li>
            <li>
              <label>手机号码</label>
              <span>{mobilePhone}</span>
              <span className="edit" onClick={this.handleEditMobile}>更换</span>
            </li>
            <li>
              <label>推荐人信息</label>
              <span>{recommendPhone}</span>
            </li>
            <li>
              <label>所在城市</label>
              <span>{city}</span>
            </li>
            {/* <li>
              <label>所属机构</label>
              <span>{orgName}</span>
            </li> */}
            <li>
              <label>所属机构</label>
              <Select 
                size="large" 
                style={{ width: 300, fontSize: 14, color: '#333' }} 
                onChange={this.handleOrgChange}
                placeholder="请选择机构"
                value={orgId}
              >
                {
                  orgList.map(org => (
                    <Option key={org.id} value={org.id}>{org.orgName}</Option>
                  ))
                }
              </Select>
            </li>
          </ul>
          <div className="btn-wrap">
            <span onClick={this.handleSubmit}>保存</span>
            <span>取消</span>
          </div>
        </div>
      </div>
    )
  }
}